
<div>
    <a href="{ADMINSCRIPT}?action=plugins&operation=config&do=133&identifier=erling_kami_buy&pmod=admin_config&type=site">
        <button type="button" class="btn">
            <i class="icon icon-cog"></i> 基本配置
        </button>
    </a>
    <a href="{ADMINSCRIPT}?action=plugins&operation=config&do=133&identifier=erling_kami_buy&pmod=admin_config&type=api_site">
        <button type="button" class="btn">
            <i class="icon icon-list"></i> 请求接口时配置
        </button>
    </a>
</div>
<form method="post" action="{ADMINSCRIPT}?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_kami_buy&pmod=admin_config">
    <input type="hidden" name="formhash" value="{FORMHASH}">
    <table class="tb tb2">
        <tr><th>配置名称</th><th>配置值</th><th>配置说明</th></tr>
        <!--{loop $configs $config}-->
        <!--{if !in_array($config['key'], ['position_float_value', 'position_float_color', 'position_float_bgcolor'])}-->
        <tr>
            <td>{$config['name']}</td>
            <td>
            <!--{if $config['key'] == 'allowed_groups'}-->
                <!--{eval 
                    $allowed_groups = dunserialize($config['value']);
                }-->
                <select name="config[{$config['key']}][]" multiple="multiple" style="height:200px;width:200px;">
                    <option value="clear" onclick="this.parentNode.querySelectorAll('option').forEach(opt => opt.selected = false); this.selected = true">-- 清空选择 --</option>
                    
                    <!-- 会员用户组 -->
                    <optgroup label="会员用户组">
                        <!--{loop $member_groups $group}-->
                        <option value="{$group['groupid']}" <!--{if is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups)}-->selected<!--{/if}-->>{$group['grouptitle']}</option>
                        <!--{/loop}-->
                    </optgroup>
                    
                    <!-- 管理用户组 -->
                    <optgroup label="系统用户组">
                        <!--{loop $system_groups $group}-->
                        <option value="{$group['groupid']}" <!--{if is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups)}-->selected<!--{/if}-->>{$group['grouptitle']}</option>
                        <!--{/loop}-->
                    </optgroup>

                    <!-- 自定义管理组 -->
                    <optgroup label="自定义管理组">
                        <!--{loop $admin_groups $group}-->
                        <option value="{$group['groupid']}" <!--{if is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups)}-->selected<!--{/if}-->>{$group['grouptitle']}</option>
                        <!--{/loop}-->
                    </optgroup>
                    
                    <!-- 自定义用户组 -->
                    <optgroup label="自定义用户组">
                        <!--{loop $special_groups $group}-->
                        <option value="{$group['groupid']}" <!--{if is_array($allowed_groups) && in_array($group['groupid'], $allowed_groups)}-->selected<!--{/if}-->>{$group['grouptitle']}</option>
                        <!--{/loop}-->
                    </optgroup>
                </select>
                <script>
                document.currentScript.parentNode.querySelector('select').addEventListener('change', function(e) {
                    if(e.target.querySelector('option[value="clear"]:checked')) {
                        e.target.querySelectorAll('option').forEach(opt => opt.selected = false);
                    }
                });
                </script>
            <!--{elseif in_array($config['key'], ['kami_expire_time', 'kami_length'])}-->
                <input type="number" name="config[{$config['key']}]" value="{$config['value']}" min="1" />
                  <!--{if $config['key']=='kami_expire_time'}-->
                    <span>天</span>
                  <!--{/if}-->
            <!--{elseif $config['key'] == 'kami_char_type'}-->
                <!--{eval 
                    $char_types = json_decode($config['value'], true);
                    $char_type_labels = ['数字', '小写字母', '大写字母', '特殊字符'];
                }-->
                <!-- 循环遍历字符类型标签 -->
                <!--{loop $char_type_labels $index $label}-->
                    <label>
                        <input 
                            type="checkbox" 
                            name="config[{$config['key']}][]" 
                            value="1" 
                            <!--{if isset($char_types[$index]) && $char_types[$index] == '1'}-->checked<!--{/if}-->
                        />
                        {$label}
                    </label>
                <!--{/loop}-->
            <!--{elseif $config['key'] == 'kami_format'}-->
                <input 
                    type="text" 
                    name="config[{$config['key']}]" 
                    value="{$config['value']}" 
                    id="kami_format_input"
                    oninput="validateKamiFormat(this)"
                />
                <span id="kami_format_error" style="color: #ff5353; display: none;">输入内容不为空时必须包含 X</span>
            <!--{elseif $config['key'] == 'nav_position'}-->
                <select name="config[{$config['key']}]">
                    <option value="">-- 不显示 --</option>
                    <option value="global_cpnav_extra1" <!--{if $config['value'] == 'global_cpnav_extra1'}-->selected<!--{/if}-->>左上顶部</option>
                    <option value="global_usernav_extra3" <!--{if $config['value'] == 'global_usernav_extra3'}-->selected<!--{/if}-->>用户导航栏</option>
                    <option value="global_nav_extra" <!--{if $config['value'] == 'global_nav_extra'}-->selected<!--{/if}-->>主导航栏</option>
                </select>
            <!--{elseif $config['key'] == 'precautions' || $config['key'] == 'kami_api_private_key'}-->
                <textarea name="config[{$config['key']}]" style="width: 300px; height: 100px;"><!--{if $config['key'] != 'kami_api_private_key'}-->{$config['value']}<!--{/if}--></textarea>
            <!--{elseif $config['key'] == 'kami_api'}-->
                <label>
                    <input type="radio" name="config[{$config['key']}]" value="1" <!--{if $config['value'] == '1'}-->checked<!--{/if}--> /> 是
                </label>
                <label>
                    <input type="radio" name="config[{$config['key']}]" value="0" <!--{if $config['value'] == '0'}-->checked<!--{/if}--> /> 否
                </label>
            <!--{elseif $config['key'] == 'kami_api_private_key'}-->
                <input type="text" name="config[{$config['key']}]" value="" />
            <!--{elseif $config['key'] == 'kami_api_site_credit'}-->
                <input type="text" name="config[{$config['key']}]" value='{$config["value"]}' />
                <span onclick="getKamiApiUrl()" style="background-color: #f4f4f4;padding: 5px;border: 1px #5a5a5a solid;border-radius: 3px;cursor: pointer;">点击请求设置</span>
                <script>
                    function getKamiApiUrl() {
                        const input = document.querySelector('input[name="config[kami_api_url]"]');
                        if(input) {
                            fetch(input.value)
                                .then(response => response.json())
                                .then(data => {
                                    console.log('API响应:', data);
                                    // 从data.data的列表中截取id和name,然后
                                    // [{id: 1, name: '测试',extcredits: '', credit: ''}, {id: 2, name: '测试2',extcredits: '', credit: ''}]
                                    // 然后弹窗遍历，用户可修改每列的extcredits和credit，点击确认后输出为json，填到kami_api_site_credit中
                                    if(data && data.data && Array.isArray(data.data)) {
                                        const siteCredit = data.data.map(item => ({
                                            id: item.id,
                                            name: item.name,
                                            extcredits: '',
                                            credit: ''
                                        }));
                                        showCreditEditor(siteCredit);
                                    }
                                })
                                .catch(error => {
                                    console.error('请求错误:', error);
                                });
                        }
                    }
                </script>
            <!--{else}-->
                <input type="text" name="config[{$config['key']}]" value="{$config['value']}" />
            <!--{/if}-->
            </td>
            <td>{$config['desc']}</td>
        </tr>
        <!--{/if}-->
        <!--{/loop}-->
    </table>
    <input type="submit" class="btn" name="configsubmit" value="提交保存" />
</form>

<script>
    function validateKamiFormat(input) {
        const value = input.value;
        const errorSpan = document.getElementById('kami_format_error');
        if (errorSpan) {
            if (value !== '' && !value.includes('X')) {
                errorSpan.textContent = '输入内容不为空时必须包含 X';
                errorSpan.style.display = 'inline';
            } else {
                errorSpan.style.display = 'none';
            }
        }
    }

    // 表单提交时验证
    document.querySelector('form').addEventListener('submit', function(e) {
        const kamiFormatInput = document.getElementById('kami_format_input');
        const errorSpan = document.getElementById('kami_format_error');
        if (errorSpan && kamiFormatInput) {
            const value = kamiFormatInput.value;
            if (value !== '' && !value.includes('X')) {
                errorSpan.style.display = 'inline';
                e.preventDefault(); 
            }
        }
    });

    // 显示api积分设置弹窗
    function showCreditEditor(data) {
        let dialog = document.createElement('div');
        dialog.className = 'credit-editor';
        
        // 构建HTML内容
        let html = '<h3>编辑积分设置</h3>';
        html += '<div style="max-height: 200px;overflow-y: auto;"><table><tr><th>ID</th><th>名称</th><th>积分类型</th><th>积分值</th></tr>';
        
        data.forEach(item => {
            html += `<tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>{$html_selectapi_extcredits}</td>
                <td><input type="text" value="${item.credit || ''}" class="api-credit"></td>
            </tr>`;
        });
        
        html += '</table></div>';
        html += '<div class="button-group">';
        html += '<button class="confirm-btn">确认</button>';
        html += '<button class="cancel-btn">取消</button>';
        html += '</div>';
        
        dialog.innerHTML = html;
        
        // 添加到body
        document.body.appendChild(dialog);
        
        // 添加事件监听
        dialog.querySelector('.confirm-btn').addEventListener('click', function() {
            let result = [];
            let rows = dialog.querySelectorAll('tr');
            
            for(let i = 1; i < rows.length; i++) {
                let cells = rows[i].querySelectorAll('td');
                if(cells.length > 0) {
                    result.push({
                        id: parseInt(cells[0].textContent),
                        name: cells[1].textContent,
                        extcredits: rows[i].querySelector('.api-extcredits').value,
                        credit: rows[i].querySelector('.api-credit').value
                    });
                }
            }
            
            document.querySelector('input[name="config[kami_api_site_credit]"]').value = JSON.stringify(result);
            document.body.removeChild(dialog);
        });
        
        dialog.querySelector('.cancel-btn').addEventListener('click', function() {
            document.body.removeChild(dialog);
        });
    }
</script>
<style>
.credit-editor {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    border: 1px solid #ccc;
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    z-index: 9999;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    overflow: auto;
}
.credit-editor table {
    width: 100%;
    border-collapse: collapse;
}
.credit-editor th, .credit-editor td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}
.credit-editor button {
    padding: 8px 15px;
    margin-right: 10px;
    cursor: pointer;
}
.credit-editor .button-group{
    text-align: right;
    margin-top: 15px;
}
</style>